<template>
    <view class="uni-list-container" @scroll="onPageScroll">
        <view class="image-item" v-for="(item,index) in list" :key="index">
            <image class="image" mode="widthFix" :class="{lazy:!item.show}" :data-index="index" @load="imageLoad" :src="item.show?item.src:placeholderSrc" />
        </view>
        <uni-icons class="icon-to-top" type="pulldown" color="#007aff" size="25" v-show="topIconShow" @click="toTop()"/>
    </view>
</template>

<script>
export default {
  data() {
    var imgs = ['shuijiao', 'muwu', 'cbd']
    var list = []
    for (let i = 0; i < 14; i++) {
        list.push({
            src: `https://img-pre.ivsky.com/img/tupian/pre/201810/07/youhua${i==0 ? '':'-00'+i}.jpg`,
            show: false,
            loaded: false
        })
    }
    return {
        windowHeight: 0,
        placeholderSrc: '/static/test/manhua.png',
        list: list,
        show: false,
        topIconShow: false
    }
  },
  methods: {
    //监听滚动事件
    onPageScroll(e){
      this.topIconShow = e.scrollTop >= this.windowHeight
    },
    //滚动视图顶部
    toTop() {
      uni.pageScrollTo({
        scrollTop: 0,
        duration: 300
      })
    },
    load() {
      //创建一个节点抓取对象，但需要再mounted()之后调用
      // boundingClientRect(callback)，添加节点的布局位置的查询请求
      uni.createSelectorQuery().selectAll('.lazy').boundingClientRect((images) => {
          images.forEach((image, index) => {
              if (image.top <= this.windowHeight) {
                  this.list[image.dataset.index].show = true;
              }
          })
      }).exec()
    },
    imageLoad(e) {
      this.list[e.target.dataset.index].loaded = true
    }
  },
  onLoad() {
    //获取当前操作系统信息
    this.windowHeight = uni.getSystemInfoSync().windowHeight

  },
  onShow() {
    if (!this.show) {
        this.show = true
        // this.$nextTick(()=>{
        //   this.load()
        // })
        setTimeout(() => {
            this.load()
        }, 100)
    }

  },
  onPageScroll() {
    this.load()
  }
}
</script>

<style lang="scss" scoped>
.uni-list-container {
  width: 100%;
  height: 100%;
  display: flex;
  flex-direction: column;
  align-items: center;
  .image-item {
    width: 100%;
    object-fit: contain;
    font-size: 0; //用于去除inline-block的间隙问题
    .image {
      width: 100%;
      height: 100%;
    }
  }
  .icon-to-top {
    position: fixed;
    right: 20rpx;
    bottom: 350rpx;
    width: 100rpx;
    height: 100rpx;
    line-height: 100rpx;
    border-radius: 50%;
    box-shadow: 0 0 10rpx #000;
    transform: rotate(-180deg);
  }
}
.placeholder {
    opacity: 1;
    transition: opacity 0.4s linear;
}

.placeholder.loaded {
    opacity: 0;
}

.uni-media-list-logo {
    position: relative;
}

.uni-media-list-logo .image {
    position: absolute;
}
</style>